//
//  COFeedController.swift
//  CocoProject
//
//  Created by Vill on 2023/11/10.
//

import UIKit
import TZImagePickerController

class COFeedController: COBaseController {
    
    lazy var containView: UIView = {
        let con = UIView()
        con.backgroundColor = .white
        return con
    }()
    
    var qaArr = [MarketQaModel]()
    var cusService = "" // 客服
    
    var feedImgStr = ""

    lazy var feedContain: UIView = {
        let feed = UIView()
        feed.layer.cornerRadius = PTW(20)
        feed.layer.masksToBounds = true
        feed.backgroundColor = UIColor.colorWithHex("#F5F5F5")
        feed.addTap { ges in
            DispatchQueue.main.safeAsync({
                let pick = TZImagePickerController(maxImagesCount: 1, delegate: self)!
                self.present(pick, animated: true)
            })
        }
        return feed
    }()
    
    lazy var cameraImg: UIImageView = {
        let avater = UIImageView()
        avater.image = KImaged("coco_feed_icon")
        return avater
    }()
    
    lazy var feedImg: UIImageView = {
        let feed = UIImageView()
        feed.contentMode = .scaleAspectFill
        feed.clipsToBounds = true
        return feed
    }()
    
    lazy var emailContain: UIView = {
        let feed = UIView()
        feed.layer.cornerRadius = PTW(65/2)
        feed.layer.masksToBounds = true
        feed.backgroundColor = UIColor.colorWithHex("#F5F5F5")
        return feed
    }()
    
    lazy var emailTxt: UITextField = {
        let hi = UITextField()
        hi.textColor = UIColor.colorWithHex("#7863A6")
        hi.backgroundColor = UIColor.clear
        hi.borderStyle = .roundedRect
        hi.font = UIFont.pingfangFont(ofSize: PTW(15), weight: .medium)
        let attributes = [NSAttributedString.Key.font:UIFont.pingfangFont(ofSize: PTW(15), weight: .medium),
                          NSAttributedString.Key.foregroundColor:UIColor.colorWithHex("#7863A6", 0.5)]
        hi.attributedPlaceholder = NSAttributedString.init(string: "Email", attributes: attributes)
        hi.modifyClearButton(KImaged("coco_editTxt_close"))
        hi.clearButtonMode = .whileEditing  //编辑时出现清除按钮
        let leftView = UIView(frame:CGRect(x: 0, y: 0, width: PTW(10), height: PTW(40)))
        hi.leftViewMode = .always
        hi.leftView = leftView
        return hi
    }()
    
    // 按钮
    lazy var doneBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = UIFont.pingfangFont(ofSize: PTW(16), weight: .bold)
        button.setTitleColor(.white, for: .normal)
        button.setTitle("Submit", for: .normal)
        button.addTap { [weak self] ges in
            guard let `self` = self else { return }
            self.doneAction()
        }
        return button
    }()
    
    lazy var feedDesTxtContain:PlaceholderTextView = {
        let place = PlaceholderTextView(placeholder: "Problem Description...", placeholderColor: UIColor.colorWithHex("#7863A6",0.5), frame: .zero)
        place.backgroundColor = UIColor.colorWithHex("#F5F5F5")
        place.palceholdertextView.textColor = UIColor.white
        place.countLabel.textColor = UIColor.colorWithHex("#7863A6")
        place.isShowCountLabel = true  // 设置是否显示计算label
        place.limitWords = 300        // 限制字数
        place.isReturnHidden = true    // 是否return关闭键盘
        place.layer.cornerRadius = PTW(20)
        place.layer.masksToBounds = true
        //防止在拼音打字时抖动
        place.palceholdertextView.layoutManager.allowsNonContiguousLayout = false
        place.translatesAutoresizingMaskIntoConstraints = false
        place.palceholdertextView.returnKeyType = .send
        place.palceholdertextView.enablesReturnKeyAutomatically = true
        return place
    }()
    
    //MARK: --------- 客服按钮 ------------
    lazy var serviceBtn: UIButton = {
        let service = UIButton(type: .custom)
        service.setImage(KImaged("coco_msg_service"), for: .normal)
        service.addTarget(self, action: #selector(serviceAction), for: .touchUpInside)
        return service
    }()
    
    lazy var redView: UIView = {
        let res = UIView()
        res.layer.cornerRadius = PTW(4)
        res.layer.masksToBounds = true
        res.backgroundColor = UIColor.colorWithHex("#FF3E32")
        res.isHidden = true
        return res
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if(self.cusService.isEmptyStr == false){
            self.clearServiceMsg(serviceId: self.cusService)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.addnav()
        self.title = "Feedback"
        setUI()
        getMarketingQaAcrion()
    }
    
    // 设置UI
    func setUI(){
        self.view.addSubview(self.containView)
        self.containView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(self.navView.snp.bottom)
        }
        self.containView.addSubview(feedContain)
        feedContain.addSubview(cameraImg)
        feedContain.addSubview(feedImg)
        self.containView.addSubview(feedDesTxtContain)
        self.containView.addSubview(emailContain)
        self.containView.addSubview(doneBtn)
        emailContain.addSubview(emailTxt)
        
        feedContain.snp.makeConstraints { make in
            make.size.equalTo(PTW(150))
            make.left.equalToSuperview().offset(PTW(20))
            make.top.equalToSuperview().offset(PTW(30))
        }
        cameraImg.snp.makeConstraints { make in
            make.size.equalTo(PTW(30))
            make.centerX.centerY.equalToSuperview()
        }
        feedImg.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        feedDesTxtContain.snp.makeConstraints { make in
            make.height.equalTo(PTW(200))
            make.left.equalToSuperview().offset(PTW(20))
            make.right.equalToSuperview().offset(-PTW(20))
            make.top.equalTo(feedContain.snp.bottom).offset(PTW(20))
        }
        emailContain.snp.makeConstraints { make in
            make.height.equalTo(PTW(65))
            make.left.equalToSuperview().offset(PTW(20))
            make.right.equalToSuperview().offset(-PTW(20))
            make.top.equalTo(feedDesTxtContain.snp.bottom).offset(PTW(20))
        }
        doneBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: PTW(225), height: PTW(65)))
            make.centerX.equalToSuperview()
            make.top.equalTo(emailContain.snp.bottom).offset(PTW(50))
        }
        emailTxt.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(PTW(5))
            make.top.bottom.equalToSuperview()
            make.trailing.equalToSuperview().offset(-PTW(5))
        }
        
        self.view.addSubview(self.serviceBtn)
        self.view.addSubview(self.redView)
        self.serviceBtn.snp.makeConstraints { make in
            make.size.equalTo(PTW(44))
            make.centerY.equalTo(self.titleLabel)
            make.right.equalToSuperview().offset(-PTW(15))
        }
        self.redView.snp.makeConstraints { make in
            make.size.equalTo(PTW(8))
            make.top.right.equalTo(self.serviceBtn)
        }
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.containView.clipsCorners(corners: [.topLeft,.topRight], radius: PTW(30))
        self.doneBtn.clipsAllCorners(radius: PTW(65/2))
        self.doneBtn.backgroundColor = UIColor.gradientFromColor(colors: [UIColor.colorWithHex("#7038FF").cgColor,UIColor.colorWithHex( "#FF3DE1").cgColor], direction: .Horizontal, range: PTW(225))
    }
    
    func doneAction(){
        if self.feedDesTxtContain.palceholdertextView.text.isEmptyStr == true{
            UIToolHelper.makeToast("please input something")
            return
        }
        if self.emailTxt.text?.isEmptyStr == true{
            UIToolHelper.makeToast("please input your email")
            return
        }
        if self.emailTxt.text?.isEmail() == true{
            UIToolHelper.makeToast("Please enter a valid email")
            return
        }
        let model = COUserInfoManager.shared.curUser
        var params = [String:Any]()
        params["streamerId"]     =  model?.userResponse.id
        params["reason"]         =  self.feedDesTxtContain.palceholdertextView.text
        if self.feedImgStr.isEmptyStr == false {
            params["pictureAddress"] =  self.feedImgStr
        }
        UIToolHelper.showHUD()
        COHttpManager.request(target: COBaseApi.feedbackNew(param: params), modelType: CONSObjectModel.self) { [weak self] code, object, success in
            UIToolHelper.hideHUD()
            UIToolHelper.makeToast("Thanks！We will solve this problem as soon as possible.")
            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                self?.navigationController?.popViewController(animated: true)
            }
        } failureBlock: { code, msg in
            UIToolHelper.hideHUD()
        }
    }
    
    func getMarketingQaAcrion(){
        var params = [String:Any]()
        params["pageNum"]  = 1
        params["pageSize"] = 100
        COHttpManager.request(target: COBaseApi.marketQa(param: params), modelType: COMarketQaDatasModel.self) { [weak self]code, object, success in
            self?.qaArr.removeAll()
            let tempArr = object?.pageData
            for i in 0..<(tempArr?.count ?? 0) {
                let qamodel = tempArr![i] as MarketQaModel
                if (qamodel.id == 1){
                    self?.cusService = "streamer_\(qamodel.answer)"
                    kCustomerService.keySaveToNSDefaults(with: self?.cusService)
                    self?.clearServiceMsg(serviceId: self!.cusService)
                }else{
                    self?.qaArr.append(qamodel)
                }
            }
        } failureBlock: {code, msg in
            print("\(msg ?? "")")
        }
    }
    
    //MARK: --------- 客服点击 ------------
    @objc func serviceAction(){
        if(self.cusService.isEmptyStr == true){
            UIToolHelper.makeToast("Customer service is busy now, please try again later!")
            return
        }
        let chat = COServiceViewController()
        chat.targetId = self.cusService
        chat.qaArr = self.qaArr
        chat.conversationType = .ConversationType_PRIVATE
        chat.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(chat, animated: true)
        RCIMClient.shared().clearMessagesUnreadStatus(.ConversationType_PRIVATE, targetId: chat.targetId)
        self.redView.isHidden = true
    }
    
    func clearServiceMsg(serviceId:String){
        let count = RCIMClient.shared().getUnreadCount(.ConversationType_PRIVATE, targetId: self.cusService)
        self.redView.isHidden = count > 0 ? false:true
    }
}

extension COFeedController: TZImagePickerControllerDelegate {
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool, infos: [[AnyHashable : Any]]!) {
        self.view.endEditing(true)
        let img = photos.first
        changeMyAvater(img)
    }
    
    // 上传头像
    func changeMyAvater(_ image:UIImage?){
        let uploadImageData = compressImageToData(image)
        UIToolHelper.showHUD()
        COHttpManager.request(target: COBaseApi.uploadData(data: uploadImageData ?? Data.init()), modelType: UploadResponseModel.self) {[weak self] code, object, success in
            UIToolHelper.hideHUD()
            self?.feedImg.image = image
        } failureBlock: { code, msg in
            UIToolHelper.hideHUD()
        }
    }
    
    func compressImageToData(_ img:UIImage?) -> Data? {
        var data = img?.jpegData(compressionQuality: 1.0)
        if (data?.count ?? 0) > 100 * 1024 {
            if (data?.count ?? 0) > 1024 * 1024 {
                //1M以及以上
                data = img?.jpegData(compressionQuality: 0.1)
            } else if (data?.count ?? 0) > 512 * 1024 {
                //0.5M-1M
                data = img?.jpegData(compressionQuality: 0.5)
            } else if (data?.count ?? 0) > 200 * 1024 {
                //0.25M-0.5M
                data = img?.jpegData(compressionQuality: 0.9)
            }
        }
        return data
    }
}
